package cn.springcloud.fix.gateway.handler;

import com.google.code.kaptcha.Producer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 验证码生成逻辑处理类
 */
@Slf4j
@Component
@AllArgsConstructor
public class ImageCodeHandler implements HandlerFunction<ServerResponse> {

    private final Producer producer;

    private final StringRedisTemplate redisTemplate;

    @Override
    public Mono<ServerResponse> handle(ServerRequest serverRequest) {
        String text = producer.createText();//生成验证码
        BufferedImage image = producer.createImage(text);

        //保存验证码信息
        String randomStr = null;
        Optional<String> optional = serverRequest.queryParam("randomStr");
        if (optional.isPresent()) {
            randomStr = optional.get();
        }

        redisTemplate.opsForValue().set("DEFAULT_CODE_KEY_" + randomStr, text, 60, TimeUnit.SECONDS);

        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpeg", os);
        } catch (IOException e) {
            log.error("ImageIO write err", e);
            return Mono.error(e);
        }

        return ServerResponse
                .status(HttpStatus.OK)
                .contentType(MediaType.IMAGE_JPEG)
                .header("randomStr", randomStr)
                .body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));

        // return ServerResponse
        //         .status(HttpStatus.OK)
        //         .contentType(MediaType.APPLICATION_JSON_UTF8)
        //         .body(BodyInserters.fromObject("ok"));
    }
}
